// 现⿏标放在头像框，出现下拉框
const user = document.querySelector('.user')
function frameenter() {
  user.nextElementSibling.style.display = 'block'
  user.nextElementSibling.nextElementSibling.style.display = 'block'
}
function frameleave() {
  user.nextElementSibling.style.display = 'none'
  user.nextElementSibling.nextElementSibling.style.display = 'none'
}
user.addEventListener('mouseenter', frameenter)
user.addEventListener('mouseleave', frameleave)
user.nextElementSibling.addEventListener('mouseenter', frameenter)
user.nextElementSibling.addEventListener('mouseleave', frameleave)
user.nextElementSibling.nextElementSibling.addEventListener('mouseenter', frameenter)
user.nextElementSibling.nextElementSibling.addEventListener('mouseleave', frameleave)

// 点击头像，出现登录模态框
const box = document.querySelector('.background-shadow')
const closebtn = document.querySelector('.icon-shanchu')
user.addEventListener('click', () => {
  box.style.display = 'block'
})
closebtn.addEventListener('click', () => {
  box.style.display = 'none'
})

// 封装函数
function myAxios(config) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    if (config.params) {
      const paramsObj = new URLSearchParams(config.params)
      const queryString = paramsObj.toString()
      config.url += `?${queryString}`
    }
    xhr.open(config.method || 'get', config.url)
    xhr.addEventListener('loadend', () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.response))
      } else {
        reject(new Error(xhr.response))
      }
    })
    if (config.headers) {
      Object.keys(config.headers).forEach(key => {
        xhr.setRequestHeader(key, config.headers[key])
      })
    }
    if (config.data instanceof FormData) {
      xhr.send(config.data)
    } else if (config.data) {
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.send(JSON.stringify(config.data))
    } else {
      xhr.send()
    }
  })
}
// 收藏
const collectBox = document.createElement('div')
collectBox.classList.add('tip')
document.querySelector('.tencent').appendChild(collectBox)

myAxios({
  url: 'https://blog.zifeiyu.love/video/query',
  params: {
    id: localStorage.getItem('id')
  },
  headers: {
    token: localStorage.getItem('token')
  }
}).then(result => {
  // 电视剧要展⽰对应剧集
  if (result.data.type === '电视剧') {
    let liStr = ''
    for (let i = 0; i < result.data.allCount; i++) {
      if (i === result.data.nowCount - 1) {
        liStr += `<li class="active" data-id="${i}"><span class="num">${i + 1}</span></li>`
        myAxios({
          url: 'https://blog.zifeiyu.love/video/queryEpisode',
          params: {
            id: localStorage.getItem('id')
          },
          headers: {
            token: localStorage.getItem('token')
          }
        }).then(result => {
          document.querySelector('.video video').src = result.data[i].url
          getComment(result.data[i].id)
        })
      } else {
        liStr += `<li data-id="${i}"><span class="num">${i + 1}</span></li>`
      }
    }
    document.querySelector('.detail').innerHTML = `
            <div class="playlist-intro">
              <div class="playlist-intro-left">
                <img src="${result.data.cover}" alt="">
              </div>
              <div class="playlist-intro-right">
                <div class="playlist-intro-title">
                  <h2>${result.data.name}</h2>
                  <div class="playlist-intro-detail">
                    <span>简介</span>
                    <i class="iconfont icon-xiangyoulajiantou"></i>
                  </div>
                </div>
                <div class="playlist-intro-type">
                  <i class="iconfont icon-redu"></i>
                  <span>${result.data.hotpot}·${result.data.releasePlace}·${result.data.releaseTime}</span>
                </div>
                <div class="playlsit-intro-actor">${result.data.tag}</div>
                <div class="playlist-intro-episode">更新至0${result.data.allCount}集</div>
              </div>
            </div>
            <div class="playlist-update">${result.data.daily}·<a>追剧日历<i
                  class="iconfont icon-xiangyoulajiantou"></i></a></div>
            <div class="playlist-action">
              <i class="iconfont icon-menu-left"></i>
              <i class="iconfont icon-pinglun1"></i>
              <i class="iconfont icon-gengduo"></i>
            </div>
            <div class="playlist-tv">
              <ul>
                ${liStr}
              </ul>
            </div>
    `
    // 切换具体剧集
    document.querySelector('.playlist-tv').addEventListener('click', (e) => {
      const li = e.target.closest('li')
      if (li) {
        document.querySelectorAll('.playlist-tv .active').forEach(item => {
          item.classList.remove('active')
        })
        li.classList.add('active')
      }
      myAxios({
        url: 'https://blog.zifeiyu.love/video/queryEpisode',
        params: {
          id: localStorage.getItem('id')
        },
        headers: {
          token: localStorage.getItem('token')
        }
      }).then(result => {
        localStorage.setItem('episodeId', result.data[e.target.dataset.id].id)
        document.querySelector('.video video').src = result.data[e.target.dataset.id].url
        getComment(result.data[e.target.dataset.id].id)
        post.addEventListener('click', function () {
          creatComment(result.data[e.target.dataset.id].id)
          tx.value = ''
          post.style.backgroundColor = ''
          word.innerHTML = '0/999'
          commentType = 'common'
        })
      })
    })
  }// 电影直接展⽰电影视频盒⼦
  else if (result.data.type === '电影') {
    document.querySelector('.detail').innerHTML = `
            <div class="playlist-intro">
              <div class="playlist-intro-left">
                <img src="${result.data.cover}" alt="">
              </div>
              <div class="playlist-intro-right">
                <div class="playlist-intro-title">
                  <h2>${result.data.name}</h2>
                  <div class="playlist-intro-detail">
                    <span>简介</span>
                    <i class="iconfont icon-xiangyoulajiantou"></i>
                  </div>
                </div>
                <div class="playlist-intro-type">
                  <i class="iconfont icon-redu"></i>
                  <span>${result.data.hotpot}·${result.data.releasePlace}·${result.data.releaseTime}</span>
                </div>
                <div class="playlsit-intro-actor">${result.data.tag}</div>
              </div>
            </div>
            <div class="playlist-action">
              <i class="iconfont icon-menu-left"></i>
              <i class="iconfont icon-pinglun1"></i>
              <i class="iconfont icon-gengduo"></i>
            </div>
            <div class="playlist-film">
              <img src="${result.data.cover}">
              <span>${result.data.name}</span>
            </div>
    `
    myAxios({
      url: 'https://blog.zifeiyu.love/video/queryEpisode',
      params: {
        id: localStorage.getItem('id')
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      localStorage.setItem('episodeId', result.data[0].id)
      document.querySelector('.video video').src = result.data[0].url
      getComment(result.data[0].id)
      post.addEventListener('click', function () {
        creatComment(result.data[0].id)
        tx.value = ''
        post.style.backgroundColor = ''
        word.innerHTML = '0/999'
        commentType = 'common'
      })
    })
  }
  // 收藏
  let flag = false
  document.querySelector('.playlist-action .icon-menu-left').addEventListener('click', function () {
    myAxios({
      url: 'https://blog.zifeiyu.love/video/star',
      params: {
        id: localStorage.getItem('id')
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      if (!flag) {
        this.style.color = '#08B4B4'
        flag = true
      } else {
        this.style.color = '#fff'
        flag = false
      }
      collectBox.innerHTML = result.data
      collectBox.style.display = 'block'
      setTimeout(() => {
        collectBox.style.display = 'none'
      }, 2000)
    })
  })

  // 点击视频详情⻚的简介，展⽰详情
  const jianjie = document.querySelector('.jianjie')
  const enterbtn = document.querySelector('.playlist-intro-detail')
  const quitbtn = document.querySelector('.jianjie-top i')
  enterbtn.addEventListener('click', () => {
    jianjie.classList.add('in')
    jianjie.classList.remove('out')
  })
  quitbtn.addEventListener('click', () => {
    jianjie.classList.remove('in')
    jianjie.classList.add('out')
  })
})

// 登录后添删功能
if (localStorage.getItem('token')) {
  myAxios({
    url: 'https://blog.zifeiyu.love/info/query',
    headers: {
      token: localStorage.getItem('token')
    }
  }).then(result => {
    document.querySelector('.user img').src = result.data.avatar
    document.querySelector('.avatar img').src = result.data.avatar
    localStorage.setItem('userId', result.data.id)
  })
  user.removeEventListener('mouseenter', frameenter)
  user.removeEventListener('mouseleave', frameleave)
  user.removeEventListener('click', function () {
    box.style.display = 'block'
  })
  user.addEventListener('click', () => {
    setTimeout(() => {
      location.href = 'person.html'
    }, 2000)
  })
  document.querySelector('.login').style.display = 'none'
  document.querySelector('.login-text').style.display = 'block'
  document.querySelector('.speak').addEventListener('click', function () {
    document.querySelector('.long').style.display = 'none'
    document.querySelector('.textarea').style.display = 'block'
  })
}

// 自定义视频播放器
const video = document.querySelector('video')
const hide = (name) => {
  name.style.display = 'none'
}
const appear = (name) => {
  name.style.display = 'block'
}

// 暂停播放
let isPlaying = false
document.querySelector('.playPauseBtn').addEventListener('click', function () {
  if (isPlaying) {
    video.pause()
    appear(document.querySelector('.bofang'))
    hide(document.querySelector('.zanting'))
    isPlaying = false
  } else {
    video.play()
    hide(document.querySelector('.bofang'))
    appear(document.querySelector('.zanting'))
    isPlaying = true
  }
})
video.addEventListener('ended', function () {
  appear(document.querySelector('.bofang'))
  hide(document.querySelector('.zanting'))
  isPlaying = false
})

// 倍速播放
const speedText = document.querySelector('.speed-text')
const speedContainer = document.querySelector('.speed-box-container')
const speedBoxs = document.querySelectorAll('.speed-box')

// 倍速选择的现隐
speedText.addEventListener('mouseenter', function () {
  appear(speedContainer)
})
speedContainer.addEventListener('mouseenter', function () {
  appear(speedContainer)
})
speedText.addEventListener('mouseleave', function () {
  hide(speedContainer)
})
speedContainer.addEventListener('mouseleave', function () {
  hide(speedContainer)
})

// 调节倍速
speedBoxs.forEach(item => {
  item.addEventListener('click', function () {
    video.playbackRate = parseFloat(this.dataset.rate)
    document.querySelector('.speed-box-container .active').classList.remove('active')
    item.classList.add('active')
    hide(speedContainer)
  })
})

// 音量调节
const voiceButton = document.querySelector('.voiceBtn')
const volume = document.querySelector('.volumeControl')
const voiceBox = document.querySelector('.voice-box')
let currentvolume

// 音量调节的现隐
voiceButton.addEventListener('mouseenter', function () {
  voiceBox.style.visibility = 'visible'
})
voiceBox.addEventListener('mouseenter', function () {
  voiceBox.style.visibility = 'visible'
})
voiceButton.addEventListener('mouseleave', function () {
  voiceBox.style.visibility = 'hidden'
})
voiceBox.addEventListener('mouseleave', function () {
  voiceBox.style.visibility = 'hideen'
})

// 点击音量键归0或变为之前的音量
voiceButton.addEventListener('click', function () {
  if (video.muted) {
    video.muted = false
    appear(document.querySelector('.open'))
    hide(document.querySelector('.close'))
    volume.value = currentvolume
    video.volume = volume.value / 100
    document.querySelector('.voice-box span').innerHTML = volume.value
  } else {
    video.muted = true
    hide(document.querySelector('.open'))
    appear(document.querySelector('.close'))
    volume.value = 0
    document.querySelector('.voice-box span').innerHTML = '0'
  }
})

// 调节音量,归0换图标
volume.addEventListener('input', function () {
  video.volume = this.value / 100
  document.querySelector('.voice-box span').innerHTML = this.value
  currentvolume = this.value
  if (video.volume > 0) {
    appear(document.querySelector('.open'))
    hide(document.querySelector('.close'))
  } else {
    hide(document.querySelector('.open'))
    appear(document.querySelector('.close'))
  }
})

// 画中画
const smallWindow = document.querySelector('.small-window')
smallWindow.addEventListener('click', function () {
  if (video.requestPictureInPicture) {
    video.requestPictureInPicture()
  }
})
document.addEventListener('fullscreenchange', function () {
  if (document.pictureInPictureElement === null) {
    video.style.display = 'block'
  } else {
    video.style.display = 'none'
  }
})

// 进度条
let isDragging = false
const progressContainer = document.querySelector('.video-progress-list')
const progressBar = document.querySelector('.video-progress-bar')

// 时间表示形式
function formatTime(second) {
  const minutes = Math.floor(second / 60)
  const seconds = Math.floor(second % 60)
  return (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds
}

// 更新进度条
function updateBar() {
  const duration = video.duration
  const currentTime = video.currentTime
  const progress = (currentTime / duration) * 100
  progressBar.style.width = progress + '%'
  document.querySelector('.progress-start').innerHTML = formatTime(currentTime)
}

// 页面刷新初始化
video.addEventListener('loadedmetadata', function () {
  document.querySelector('.progress-start').innerHTML = '00:00'
  document.querySelector('.progress-end').innerHTML = formatTime(video.duration)
})

// 点击任一处进度跳转
progressContainer.addEventListener('click', function (e) {
  const bounds = this.getBoundingClientRect()
  const xPos = e.clientX - bounds.left
  const videoWidth = bounds.width
  const newTime = (xPos / videoWidth) * video.duration
  video.currentTime = newTime
  document.querySelector('.progress-start').innerHTML = formatTime(video.currentTime)
})

video.addEventListener('timeupdate', updateBar)

// 让mousemove启动，确认处于拉动状态，并初始化点击那一刻的状态
progressBar.addEventListener('mousedown', function (e) {
  isDragging = true
  const clickX = e.clientX
  const videoWidth = video.offsetWidth
  const newTime = ((clickX / videoWidth) * video.duration).toFixed(2)
  video.currentTime = newTime
  document.querySelector('.progress-start').innerHTML = formatTime(video.currentTime)
})

// 拉动进度条,更新不同的状态
document.addEventListener('mousemove', function (e) {
  if (isDragging) {
    const clickX = e.clientX
    const videoWidth = video.offsetWidth
    const newTime = ((clickX / videoWidth) * video.duration).toFixed(2)
    video.currentTime = newTime
    document.querySelector('.progress-start').innerHTML = formatTime(video.currentTime)
  }
})

// 结束mousemove
document.addEventListener('mouseup', function () {
  isDragging = false
})

// 创建弹幕
function createdanmaku(id, content) {
  myAxios({
    url: 'https://blog.zifeiyu.love/barrage',
    method: 'post',
    data: {
      episodeId: id,
      happenTime: '',
      content: content
    },
    headers: {
      token: localStorage.getItem('token')
    }
  }).then(result => {
    alert(result.data)
    const layer = getRandomLayer()
    const danmaku = document.createElement('div')
    danmaku.className = 'danmaku'
    danmaku.style.top = `${(40 / numLayers) * layer}%`
    danmaku.style.color = getRandomColor()
  })
  return danmaku
}

const speed = 100
const numLayers = 4
const colorOption = ['red', 'yellow', 'white', 'blue', 'pink', 'purple']
function getRandomColor() {
  return colorOption[Math.floor(Math.random() * colorOption.length)]
}
function getRandomLayer() {
  return Math.floor(Math.random() * numLayers) + 1
}

// 获得弹幕
function getdanmaku(id) {
  myAxios({
    url: 'https://blog.zifeiyu.love/barrage',
    params: {
      episodeId: id
    },
    headers: {
      token: localStorage.getItem('token')
    }
  }).then(result => {
    result.data.forEach(item => {
      const layer = getRandomLayer()
      const danmaku = document.createElement('div')
      danmaku.className = 'danmaku'
      danmaku.textContent = item.content
      danmaku.style.animationDuration = `${document.querySelector('.video').offsetWidth / speed}s`
      danmaku.style.animationDelay = Math.random() * video.duration + 's'
      danmaku.style.top = `${(40 / numLayers) * layer}%`
      danmaku.style.color = getRandomColor()
      document.querySelector('.video').appendChild(danmaku)
      danmaku.addEventListener('mouseenter', function () {
        this.style.animationPlayState = 'paused'
      })
      danmaku.addEventListener('mouseleave', function () {
        danmaku.style.animationPlayState = 'running'
      })
      removeDanmaku(danmaku)
    })
  })
}

// 移除弹幕
function removeDanmaku(danmaku) {
  const rect = danmaku.getBoundingClientRect()
  if (rect.right <= 0) {
    danmaku.remove()
  } else {
    setTimeout(() => removeDanmaku(danmaku), 1000 / 60)
  }
}

// 弹幕开关
let isDanmu = false
document.querySelector('.danmuBtn').addEventListener('click', function () {
  if (isDanmu) {
    hide(document.querySelector('.kai'))
    appear(document.querySelector('.guan'))
    const danmakus = document.querySelectorAll('.danmaku');
    danmakus.forEach(danmaku => {
      danmaku.remove()
    })
    isDanmu = false
  } else {
    appear(document.querySelector('.kai'))
    hide(document.querySelector('.guan'))
    getdanmaku(localStorage.getItem('episodeId'))
    isDanmu = true
  }
})

// 发布评论
const tx = document.querySelector('.textarea textarea')
const post = document.querySelector('.textarea-footer button')
const word = document.querySelector('.textarea-footer span')
tx.addEventListener('input', function () {
  const hasContent = this.value.trim().length > 0
  post.style.backgroundColor = hasContent ? '#00c8c8' : ''
  post.disabled = !hasContent
  word.innerHTML = hasContent ? `${this.value.trim().length}/999` : '0/999'
})


// 获取评论，待全部promise全部成功后渲染
function getComment(id) {
  myAxios({
    url: 'https://blog.zifeiyu.love/talk',
    params: {
      episodeId: id
    },
    headers: {
      token: localStorage.getItem('token')
    }
  }).then(result => {
    const promises = result.data.map(item => {
      return myAxios({
        url: 'https://blog.zifeiyu.love/talk/children',
        params: {
          talkId: item.id
        },
        headers: {
          token: localStorage.getItem('token')
        }
      }).then(childResult => {
        return childResult.data
      })
    })
    return Promise.all(promises)
  }).then(allData => {
    init(allData)
  })
}

// 封装二级评论类
class childrenUI {
  constructor(data) {
    this.data = data
  }

  addLike(id) {
    if (this.data.isLike) {
      this.data.likeCount--
      if (this.data.likeCount === 0) {
        this.data.likeCount = '点赞'
      }
      this.data.isLike = false
    } else {
      if (this.data.likeCount === '点赞') {
        this.data.likeCount = 1
      } else {
        this.data.likeCount++
      }
      this.data.isLike = true
    }
    myAxios({
      url: 'https://blog.zifeiyu.love/talk/like',
      method: 'put',
      params: {
        like: this.data.isLike,
        talkId: id
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      alert(result.data)
    })
  }
}

// 封装一级评论类
class fatherUI {
  constructor(data) {
    this.data = data
    this.children = []
  }

  addLike(id) {
    if (this.data.isLike) {
      this.data.likeCount--
      if (this.data.likeCount === 0) {
        this.data.likeCount = '点赞'
      }
      this.data.isLike = false
    } else {
      if (this.data.likeCount === '点赞') {
        this.data.likeCount = 1
      } else {
        this.data.likeCount++
      }
      this.data.isLike = true
    }
    myAxios({
      url: 'https://blog.zifeiyu.love/talk/like',
      method: 'put',
      params: {
        like: this.data.isLike,
        talkId: id
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      alert(result.data)
    })
  }

  setUpChild() {
    this.data.children.forEach(item => {
      const childData = new childrenUI(item)
      this.children.push(childData)
    })
  }

  getChildrenComment() {
    return this.children.length
  }

  getChildrenInstance(id) {
    const childInstance = document.querySelector('#ins-' + this.data.id + '_' + id)
    let target
    this.children.forEach((item) => {
      if (id === item.data.id) {
        target = item
      }
    })
    return {
      childInstance,
      target
    }
  }
}

// 封装整个评论类
class totalUI {
  constructor(data) {
    this.data = data
    this.children = []
  }

  setUpChild() {
    this.data.forEach((item) => {
      const childData = new fatherUI(item)
      this.children.push(childData)
    })
    this.children.forEach((item) => {
      item.setUpChild()
    })
  }

  getTotalComment() {
    let commentCount = 0
    this.children.forEach((item) => {
      const count = item.getChildrenComment()
      commentCount = commentCount + count + 1
    })
    return commentCount
  }

  getChildrenInstance(id) {
    const childInstance = document.querySelector('#ins-' + id)
    let target
    this.children.forEach((item) => {
      if (id === item.data.id) {
        target = item
      }
    })
    return {
      childInstance,
      target
    }
  }
}

const commentCount = document.querySelector('.cmtCount')
const cmtContainer = document.querySelector('.cmtContainer')
let comment
// 创建一个总评对象
const init = (data) => {
  comment = new totalUI(data)
  comment.setUpChild()
  render(comment)
}

// 渲染函数
const render = (data) => {
  let totalDOM = ''
  data.children.forEach((item) => {
    let childrenDOM = ''
    item.children.forEach((it) => {
      let DOM = `
                <div class="child" id="ins-${item.data.id}_${it.data.id}" data-id="${item.data.id}_${it.data.id}">
                  <div class="child-avadar">
                    <span class="child-name">${it.data.userInfo.username}</span>
                    <span class="time-place">${it.data.createdTime}</span>
                  </div>
                  <div class="child-main">
                    <div class="child-text">${it.data.content}</div>
                    <div class="child-function">
                      <div class="like">
                        ${it.data.isLike ? '<i class="iconfont icon-aixin1 active" data-id=' + item.data.id + '_' + it.data.id + '></i>' : '<i class="iconfont icon-aixin1" data-id=' + item.data.id + '_' + it.data.id + '></i>'}
                        <span>${it.data.likeCount === 0 ? '点赞' : it.data.likeCount}</span>
                      </div>
                      <div class="comment">
                        <i class="iconfont icon-pinglun" data-id="${item.data.id}_${it.data.id}"></i>
                        <span>评论</span>
                      </div>
                      <div class="delete">${it.data.userId == localStorage.getItem('userId') ? '<i class="iconfont icon-shanchu1" data-id=' + item.data.id + '_' + it.data.id + '></i><span>删除</span>' : ''}
                      </div>
                    </div>
                  </div>
                </div>
          `
      childrenDOM += DOM
    })

    let fatherDOM = `
            <div class="parent" id="ins-${item.data.id}" data-id="${item.data.id}">
              <div class="parent-avadar">
                <img src="${item.data.userInfo.avatar}" alt="">
                <span class="parent-name">${item.data.userInfo.username}</span>
                <span class="time-place">${item.data.createdTime}</span>
              </div>
              <div class="parent-main">
                <div class="parent-text">${item.data.content}</div>
                <div class="parent-function">
                  <div class="like">
                    ${item.data.isLike ? '<i class="iconfont icon-aixin1 active" data-id=' + item.data.id + '></i>' : '<i class="iconfont icon-aixin1" data-id=' + item.data.id + '></i>'}
                    <span>${item.data.likeCount == 0 ? '点赞' : item.data.likeCount
      }</span>
                  </div>
                  <div class="comment">
                    <i class="iconfont icon-pinglun" data-id="${item.data.id}"></i>
                    <span>评论</span>
                  </div>
                  <div class="delete">
                      ${item.data.userId == localStorage.getItem('userId') ? '<i class="iconfont icon-shanchu1" data-id=' + item.data.id + '></i><span>删除</span>' : ''}
                  </div>
                </div>
              </div>
              <div class="children">${childrenDOM}</div>
            </div>
      `
    totalDOM += fatherDOM
  })
  cmtContainer.innerHTML = totalDOM
  commentCount.innerHTML = `${data.getTotalComment()}`
  // 渲染之后为所有的function赋能
  addLikefunc()
  addCommentfunc()
  addDeletefunc()
}

let commentType = 'common'
// 创建评论
const creatComment = (id) => {
  if (commentType === 'common') {
    myAxios({
      url: 'https://blog.zifeiyu.love/talk',
      method: 'post',
      data: {
        fatherId: '',
        content: tx.value.trim(),
        episodeId: id
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      alert(result.data)
      getComment(id)
    })
  } else if (commentType === 'first') {
    myAxios({
      url: 'https://blog.zifeiyu.love/talk',
      method: 'post',
      data: {
        fatherId: localStorage.getItem('fatherId'),
        content: tx.value.trim(),
        episodeId: id
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      alert(result.data)
      getComment(id)
    })
  }
}

// 喜欢评论
const handleLike = (e) => {
  let likeDOM = e.currentTarget.children[0]
  let likeNUM = e.currentTarget.children[1]
  const id = likeDOM.getAttribute('data-id')
  const idArray = id.split('_')
  if (idArray.length === 1) {
    const { target } = comment.getChildrenInstance(parseInt(id))
    target.addLike(id)
    likeDOM.classList.toggle('active')
    likeNUM.innerHTML = target.data.likeCount
  } else {
    const { target } = comment.getChildrenInstance(parseInt(idArray[0]))
      .target.getChildrenInstance(parseInt(idArray[1]))
    target.addLike(idArray[1])
    likeDOM.classList.toggle('active')
    likeNUM.innerHTML = target.data.likeCount
  }
}

// 为所有like提供handleLike函数
function addLikefunc() {
  const like = document.querySelectorAll('.like')
  like.forEach((item) => {
    item.addEventListener('click', handleLike)
  })
}

// 回复模块
const handleComment = (e) => {
  document.querySelector('.long').style.display = 'none'
  document.querySelector('.textarea').style.display = 'block'
  tx.focus()
  let commentDOM = e.currentTarget.children[0]
  const id = commentDOM.getAttribute('data-id')
  localStorage.setItem('fatherId', id)
  const idArray = id.split('_')
  if (idArray.length === 1) {
    commentType = 'first'
  } else {
    commentType = 'follow'
  }
}

// 为所有comment提供handleComment函数
function addCommentfunc() {
  const commentBtn = document.querySelectorAll('.comment')
  commentBtn.forEach((item) => {
    item.addEventListener('click', handleComment)
  })
}

// 删除界面打开模块
const handleOpen = (e) => {
  if (confirm('您确定要删除吗？')) {
    const id = e.currentTarget.children[0].getAttribute('data-id')
    const idArray = id.split('_')
    if (idArray.length === 1) {
      myAxios({
        url: 'https://blog.zifeiyu.love/talk',
        method: 'delete',
        params: {
          talkId: id
        },
        headers: {
          token: localStorage.getItem('token')
        }
      }).then(result => {
        alert(result.data)
        getComment(localStorage.getItem('episodeId'))
      })
    } else {
      myAxios({
        url: 'https://blog.zifeiyu.love/talk',
        method: 'delete',
        params: {
          talkId: idArray[1]
        },
        headers: {
          token: localStorage.getItem('token')
        }
      }).then(result => {
        alert(result.data)
        getComment(localStorage.getItem('episodeId'))
      })
    }
  }
}

// 为所有的delete提供handleOpen函数
function addDeletefunc() {
  const deleteBtn = document.querySelectorAll('.delete')
  deleteBtn.forEach((item) => {
    item.addEventListener('click', handleOpen)
  })
}
